import base64
import os
 
def convert_image_to_base64(image_path):
    with open(image_path, 'rb') as image_file:
        encoded_string = base64.b64encode(image_file.read())
        return encoded_string.decode('utf-8')
 
def write_base64_to_file(base64_data, output_file):
    #print(output_file)
    with open(output_file, 'a+') as file:
        file.write(base64_data)
        #file.write('\n')

def convert_images_in_directory_to_base64_2(input_directory, output_file):
    if os.path.isfile(output_file):
        os.remove(output_file)
    base64ImageDict={}
    for filename in os.listdir(input_directory):
        if filename.endswith(('.png', '.jpg', '.jpeg', '.svg', '.gif', '.tif', '.tiff')):
            image_path = os.path.join(input_directory, filename)
            base64ImageDict[filename]=convert_image_to_base64(image_path)
    write_base64_to_file('base64ImageDict=', output_file)
    write_base64_to_file(str(base64ImageDict), output_file)
 
def convert_images_in_directory_to_base64(input_directory, output_file):
    if os.path.isfile(output_file):
        os.remove(output_file)
    for filename in os.listdir(input_directory):
        if filename.endswith(('.png', '.jpg', '.jpeg', '.svg', '.gif', '.tif', '.tiff')):
            image_path = os.path.join(input_directory, filename)
            # base64_data = 'data:image;{};base64;{}'.format(
            #     filename,
            #     convert_image_to_base64(image_path)
            # )
            base64_data = '{}="{}"'.format(
                filename.split('.')[0],
                convert_image_to_base64(image_path)
            )
            write_base64_to_file(base64_data, output_file)
 
# 使用方法：
# 将这个脚本保存为convert_images_to_base64.py
# 在命令行运行，并传入输入目录和输出文件路径
# python convert_images_to_base64.py /path/to/input /path/to/output/file.txt
 
if __name__ == "__main__":
    # import argparse
    # parser = argparse.ArgumentParser(description='Convert images to Base64 and write to file.')
    # parser.add_argument('input_directory', help='the directory containing images')
    # parser.add_argument('output_file', help='the output file to write Base64 data')
    # args = parser.parse_args()
    # input_dir=args.input_directory
    # output_file=args.output_file

    input_dir='./images/'
    output_file='./images/Base64Image.py'
    convert_images_in_directory_to_base64_2(input_dir, output_file)